package com.huangliusong.web.method.suport;


import com.huangliusong.web.http.converter.properties.PropertiesHttpMessageConverter;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;

/**
 * @author huangliusong
 * @since 2018/10/5
 * {@link }
 */
public class PropertiesHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {

        return Properties.class.equals(returnType.getMethod().getReturnType());
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        //强制转换
        Properties properties=(Properties)returnValue;


        //
        ServletWebRequest servletWebRequest=(ServletWebRequest)webRequest;
        HttpServletRequest request=((ServletWebRequest)webRequest).getRequest();

        HttpServletResponse response= servletWebRequest.getResponse();
        HttpOutputMessage message=new ServletServerHttpResponse(response);

        String contentType=request.getHeader("Content-Type");
        MediaType mediaType=MediaType.parseMediaType(contentType);

        PropertiesHttpMessageConverter converter=new PropertiesHttpMessageConverter();

        converter.write(properties,mediaType,message);

        // 告知 Spring Web MVC 当前请求已经处理完毕
        mavContainer.setRequestHandled(true);

    }
}
